package pikes.peak;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.web.servlet.support.RequestContext;

import pikes.html.xhtml.Anchor;
import pikes.html.xhtml.Inline;
import pikes.html.xhtml.PCData;
import pikes.html.xhtml.text.LineBreak;
import pikes.html.xhtml.text.NonBreakingSpace;
import pikes.uri.URI;
import pikes.util.Assert;
import pikes.util.Util;

public class Label implements InlineComponent {

	public static final InlineComponent LINE_BREAK = new InlineComponent() {

		public Inline createHtml(Map model, RequestContext requestContext) throws Exception {
			return new LineBreak();
		}

	};

	public static final InlineComponent SPACE = new InlineComponent() {

		public Inline createHtml(Map model, RequestContext requestContext) throws Exception {
			return new NonBreakingSpace();
		}

	};

	private List<RequestProperty<CharSequence>> textList = new LinkedList<RequestProperty<CharSequence>>();

	private LabelStyle style = null;

	private RequestProperty<URI> uri = null;

	public Label(String text) {
		Assert.hasText(text);
		addText(text);
	}

	public Label(String text, LabelStyle style) {
		this(text);
		this.style = style;
	}

	public Label() {
	}

	public Label(LabelStyle style) {
		this.style = style;
	}

	/**
	 * @see pikes.peak.InlineComponent#createHtml(java.util.Map, org.springframework.web.servlet.support.RequestContext)
	 */
	final public Inline createHtml(Map model, RequestContext requestContext) throws Exception {

		Iterator<RequestProperty<CharSequence>> iTexts = textList.iterator();
		PCData pcdata = new PCData(iTexts.next().getValue(model, requestContext));

		while (iTexts.hasNext()) {
			pcdata.addText(iTexts.next().getValue(model, requestContext));
		}

		Inline result = pcdata;

		if (style != null) {
			result = style.applyStyle(pcdata);
		}

		if (uri != null) {
			result = new Anchor(uri.getValue(model, requestContext), result);
		}

		return result;
	}

	public void addStyle(LabelStyle style) {
		this.style = style;
	}

	public void addText(String text) {
		if (Util.hasText(text)) {
			textList.add(new ApplicationContextMessageProvider(text));
		}

	}

	public void setURI(RequestProperty<URI> uri) {
		this.uri = uri;

	}

	public void setURI(URI uri) {
		setURI(new RequestIndependentProperty<URI>(uri));

	}

	public RequestProperty<URI> getURI() {
		return uri;
	}

	public void addClickListener(ClickListener listener) {

	}
}
